﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace SerialChart
{
    public delegate void UpdateData(Byte[] data);

    public partial class Form1 : Form
    {
        SerialHelper serial;
        //SerialDataFactory serialDataFactory;
        Parser serialParser;

        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        public Form1()
        {
            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//关闭跨线程检测
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //列出可用串口
            foreach (string portName in System.IO.Ports.SerialPort.GetPortNames())
            {
                cbPortName.Items.Add(portName);
            }
            //默认选中9600波特率
            cbPortName.SelectedIndex = cbPortName.Items.Count-1;
            cbBaudRate.SelectedIndex = 5;
            //图表初始化
            chart1.ChartAreas[0].Axes[0].MajorGrid.Enabled = false;         //X轴上网格
            chart1.ChartAreas[0].Axes[1].MajorGrid.Enabled = false;         //y轴上网格
            chart1.Series[0].ChartType = SeriesChartType.Spline;
            chart1.Series[0].Color = Color.CornflowerBlue;                  //线条颜色
            chart1.Series[0].BorderWidth = 2;                               //线条粗细
            chart1.ChartAreas[0].AxisX.Maximum = 100;                       //设定x轴的最大值
            //通信初始化
            serial = new SerialHelper();
            serialParser = new Parser();
            serialParser.txtData = txtSerialData;
            serial.parser = serialParser;
            //serialDataFactory = new SerialDataFactory(serial);
            //图表刷新定时器
            timer.Interval = 100;
            timer.Tick += timer_Tick;

            tabControl1.SelectedIndex = 1;
        }

        void timer_Tick(object sender, EventArgs e)  //定时刷新图表和数据框
        {
            if (serialParser.IsDataUpdate)
            {
                serialParser.IsDataUpdate = false;

                int[] dis = new int[serialParser.DataList.Count];
                serialParser.DataList.CopyTo(dis, 0);
                chart1.Series[0].Points.DataBindY(dis);

                //if (serialParser.DataText.Length > 65535)
                //{
                //    MessageBox.Show("err");
                //}
                //string txt = serialParser.DataText.ToString();
                //txtSerialData.Text = txt;
                //txtSerialData.SelectionStart = txtSerialData.Text.Length; //Set the current caret position at the end
                //txtSerialData.ScrollToCaret(); //Now scroll it automatically
            }
            
        }

        void Proto_ByteReceived(byte[] data)
        {
            txtSerialData.BeginInvoke(new MethodInvoker(delegate()
            {
                if (rbtnASCII.Checked)
                {
                    //txtSerialData.Select();
                    this.txtSerialData.SelectionStart = txtSerialData.TextLength;
                    txtSerialData.ScrollToCaret();
                    this.txtSerialData.AppendText(string.Join("", (char)data[0]));
                }
                else if (rbtnHEX.Checked)
                {
                    //txtSerialData.Select();
                    this.txtSerialData.SelectionStart = txtSerialData.TextLength;
                    txtSerialData.ScrollToCaret();
                    this.txtSerialData.AppendText(data[0].ToString("X2") + " ");
                }
            }));  
            
        }

        public void UpdateText(Byte[] Data)
        {
            if (Data[3] == 0x01)
            {
                int s = BitConverter.ToInt16(Data, 7);
                this.chart1.Series[0].Points.Add(s);
                if (this.chart1.Series[0].Points.Count > 100)
                    this.chart1.Series[0].Points.RemoveAt(0);
            }

        }

        private void chart1_Click(object sender, EventArgs e)
        {

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void tabControl1_TabIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.TabIndex == 1)
            {

            }
        }
        bool isRun = false;
        private void btnSerialOpen_Click(object sender, EventArgs e)
        {
            try
            {
                if (isRun)
                {
                    //serialDataFactory.StopProc();
                    serial.Stop();
                    timer.Enabled = false;
                    btnSerialOpen.Text = "打开";
                    isRun = false;
                }
                else
                {
                    serial.SerialSetPortName(cbPortName.SelectedItem.ToString());
                    serial.SerialSetBaudRate(int.Parse(cbBaudRate.SelectedItem.ToString()));
                    //serialDataFactory.StartProc();
                    serial.Start();
                    timer.Enabled = true;
                    btnSerialOpen.Text = "关闭";
                    isRun = true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void 清空ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            serialParser.DataList.Clear();
            txtSerialData.Text = "";
        }

        private void 截图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            chart1.SaveImage(DateTime.Now.ToString() + ".png", ChartImageFormat.Png);
            //SaveFileDialog sfd = new SaveFileDialog();
            //sfd.InitialDirectory = "E:\\";
            //sfd.Filter = "jpg文件(*.jpg)|*.jpg|png文件(*.png)|*.png";
            //if (sfd.ShowDialog() == DialogResult.OK)
            //{
                  
            //   // textBox2.Text = sfd.FileName;
            //}
        }

        private void button1_Click(object sender, EventArgs e)
        {
            byte[] senddata = new byte[10];
            senddata[0] = 0xa5;
            senddata[1] = 0x5a;
            senddata[2] = 0x0;//addr
            senddata[3] = 0x02;//cmd
            senddata[4] = 0x0;//ext
            BitConverter.GetBytes(float.Parse(txtP.Text)).CopyTo(senddata, 5);
            senddata[9] = 0x0;
            serial.Send(senddata);
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            byte[] senddata = new byte[10];
            senddata[0] = 0xa5;
            senddata[1] = 0x5a;
            senddata[2] = 0x0;//addr
            senddata[3] = 0x03;//cmd
            senddata[4] = 0x0;//ext
            BitConverter.GetBytes(short.Parse(txtSpeed.Text)).CopyTo(senddata, 7);
            senddata[9] = 0x0;
            serial.Send(senddata);
        }

        private void btnISet_Click(object sender, EventArgs e)
        {
            byte[] senddata = new byte[10];
            senddata[0] = 0xa5;
            senddata[1] = 0x5a;
            senddata[2] = 0x00;//addr
            senddata[3] = 0x02;//cmd
            senddata[4] = 0x01;//ext
            BitConverter.GetBytes(float.Parse(txtI.Text)).CopyTo(senddata, 5);
            senddata[9] = 0x00;
            serial.Send(senddata);
        }

        private void btnDSet_Click(object sender, EventArgs e)
        {
            byte[] senddata = new byte[10];
            senddata[0] = 0xa5;
            senddata[1] = 0x5a;
            senddata[2] = 0x00;//addr
            senddata[3] = 0x02;//cmd
            senddata[4] = 0x02;//ext
            BitConverter.GetBytes(float.Parse(txtD.Text)).CopyTo(senddata, 5);
            senddata[9] = 0x00;
            serial.Send(senddata);
        }

        private void txtSerialData_TextChanged(object sender, EventArgs e)
        {
            txtSerialData.ScrollToCaret();
        }

        private void rbtnASCII_CheckedChanged(object sender, EventArgs e)
        {
            serialParser.IsHex = !rbtnASCII.Checked;
        }
    }
}
